<?php
/**
 * 微信分享组件
 */
namespace common\widgets;

use yii\base\Widget;
use services\models\wap\WeiXinToken;
use Yii;
class WeChatShareWidget extends Widget
{
    public $type;
    public static $_SHARE_CONFIG = NULL;
    public function run() {
        
      if(empty($this->type)) {
          $this->type = 'share_wap';
      }
      
      //如果不是微信浏览器返回空，不请求分享
      if(!$this->checkIsWeChatBrowser()) {
          return '';
      }
      
      if(static::$_SHARE_CONFIG == null){
            
            static::$_SHARE_CONFIG = require Yii::getAlias('@common') . '/config/share.php';
      }
       //获取当前URl
       $url  = Yii::$app->request->getHostInfo().Yii::$app->request->url;
       
       //TODO，以后可以更改为数据库查询。目前配置文件，
       $content  =  static::$_SHARE_CONFIG[$this->type];
       
       if(empty($content['link'])) {
           $content['link'] = $url;
       }
       
       $weixinToken = new  WeiXinToken();
       $signPackage = $weixinToken->getSignPackage();
       
       return  $this->render('@wap/views/layouts/wx_share',[
            'signPackage'=>$signPackage,
            'content'=>$content,
        ]);
    }
    
    
    /**
     * 检查是否是微信浏览器
     */
    private function checkIsWeChatBrowser(){
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }
    
}

?>